package com.wdl.modules.myhouse.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wdl.modules.myhouse.dto.FileDTO;
import com.wdl.modules.myhouse.entity.FileEntity;
import com.wdl.modules.myhouse.service.FileService;
import com.wdl.modules.myhouse.common.Code;
import com.wdl.modules.myhouse.common.MyPage;
import com.wdl.modules.myhouse.common.Result;
import com.wdl.modules.myhouse.vo.FileVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 昏昏的君
 */
@RestController
@RequestMapping("/file")
@Api(tags = "文件系统")
@Slf4j
public class FileController {

    @Autowired
    private FileService fileService;


    @ApiOperation(value = "根据id获取文件详细信息")
    @GetMapping("/{id}")
    public Result<FileVo> getFile(@PathVariable("id") Long id) {
        FileVo file = fileService.getFileDetailById(id);
        return new Result<FileVo>().ok().setData(file);
    }


    @ApiOperation(value = "按照上传日期统计上传文件数量")
    @GetMapping("/downloadStatistic/{year}/{month}")
    public Result downloadByDay(@PathVariable("year") Integer year, @PathVariable("month") Integer month) {
        Result<Object> res = new Result<>().ok();
        Map<String, Integer> map = fileService.downLoadstatisticByDay(year, month);
        //数据格式{2022-08-12={num=1, day=2022-08-12}}
        res.setData(map);
        return res;
    }


    @ApiOperation(value = "按照上传日期统计上传文件数量")
    @GetMapping("/static/{year}/{month}")
    public Result staticByDay(@PathVariable("year") Integer year, @PathVariable("month") Integer month) {
        Result<Object> res = new Result<>().ok();
        Map<String, Integer> map = fileService.staticByDay(year, month);
        //数据格式{2022-08-12={num=1, day=2022-08-12}}
        res.setData(map);
        return res;
    }

    @ApiOperation(value = "保存文件信息")
    @PostMapping("/save")
    public Result<Object> save(@RequestBody FileDTO dto, HttpServletRequest request) {
        String userId = request.getHeader("USER_ID");
        if (userId == null || userId.isEmpty()) {
            log.error("当前操作为匿名操作,请警惕");
        }
        try {
            FileEntity entity = new FileEntity();
            entity.setCreatorId(Integer.getInteger(userId));
            BeanUtils.copyProperties(dto, entity);
            boolean save = fileService.save(entity);
            if (save) {
                return new Result<>().ok();
            }
        } catch (BeansException e) {
            e.printStackTrace();
            Result<Object> res = new Result<>();
            res.setCode(Code.INTERNAL_ERROR.getCode());
            res.setMsg(Code.INTERNAL_ERROR.getMessage());
            return res;
        }
        return new Result<>().error();
    }


    @ApiOperation(value = "获取所有文件")
    @PostMapping("/all/{cat}")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "size", value = "页面大小", defaultValue = "10"),
            @ApiImplicitParam(name = "current", value = "当前页码", defaultValue = "1"),
            @ApiImplicitParam(name = "orders", value = "排序字段类型", dataTypeClass = List.class)
    })
    public Result<IPage<FileVo>> getAllFile(@PathVariable(value = "cat", required = false) String cat, @ApiIgnore @RequestBody MyPage page) {
        log.info("获取文件,文件类型为{}", cat);
        //todo cat合法性检验
        IPage<FileVo> page1 = fileService.getAllFileVo(page, cat);
        return new Result<IPage<FileVo>>().ok(page1);
    }


    @ApiOperation(value = "关键字查找文件")
    @PostMapping("/keyWord/{keyWord}")
    public Result<IPage<FileVo>> getFileByKeyWord(@RequestBody MyPage page, @PathVariable("keyWord") String keyWord) {
        IPage<FileVo> resPage = fileService.getFileByKeyWord(keyWord, page);
        return new Result<IPage<FileVo>>().ok(resPage);
    }

    @ApiOperation(value = "获取所有文件名")
    @GetMapping("/allNames")
    public Result<List<String>> getAllFileNames() {
        List<FileEntity> allFile = fileService.list();
        List<String> fileNames = new ArrayList<>();
        if (allFile != null && allFile.size() > 0) {
            fileNames = allFile.stream().map(file -> file.getFileName()).collect(Collectors.toList());
        }
        return new Result<List<String>>().ok(fileNames);
    }


}
